import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Spin } from 'antd';
import { CloudSyncOutlined, StopOutlined } from '@ant-design/icons';
import type { NmapVo } from './service';
import { listNmap, scanIsDone, startNmapScan, stopNmapScan } from './service';
import { useCallback, useRef, useState } from 'react';
import { hasRouteChildren } from '@/utils/utils';
import HostInfoFormModal from '../HostInfo/FormModal';
import { Link } from 'umi';
import { editPagePathname } from '@/pages/HostInfo';

export default (props: any) => {
  if (hasRouteChildren(props)) {
    return <>{props.children}</>;
  }
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);
  const [currData, setCurrData] = useState<NmapVo>();

  const columns: ProColumns<NmapVo>[] = [
    {
      title: '主机名称',
      dataIndex: 'name',
      align: 'left',
      render: (dom, entity) => {
        if (!entity.hostInfo) {
          return dom;
        }
        return (
          <>
            {dom} (
            <Link
              to={{
                pathname: editPagePathname,
                state: { primaryKey: entity.hostInfo.id },
              }}
            >
              {entity.hostInfo.name}
            </Link>
            )
          </>
        );
      },
    },
    {
      title: 'MAC 地址',
      dataIndex: 'mac',
      align: 'center',
      width: 130,
    },
    {
      title: 'IP 地址',
      dataIndex: 'ip',
      align: 'left',
      width: 130,
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      align: 'center',
      width: 80,
    },
    {
      title: '操作',
      dataIndex: 'mac',
      align: 'center',
      width: 100,
      render: (dom, entity) => {
        const length = entity.mac?.length || 0;
        return (
          <Button
            type="link"
            onClick={() => {
              setCurrData(entity);
            }}
            disabled={length < 10 || entity.hostInfo != null}
          >
            添加
          </Button>
        );
      },
    },
  ];

  const stopScan = useCallback(() => {
    setLoading(true);
    stopNmapScan()
      .then((res) => {
        message.info(res.msg);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);
  const startScan = useCallback(() => {
    setLoading(true);
    startNmapScan().then((res) => {
      message.info(res);
    });
    let retry = () => {};
    retry = () => {
      scanIsDone().then((res) => {
        if (res) {
          setLoading(false);
          actionRef.current?.reloadAndRest?.();
        } else {
          retry();
        }
      });
    };
    retry();
  }, []);

  const toolBarBtn = useCallback(() => {
    const list = [];
    list.push(
      <Button onClick={startScan} loading={loading}>
        <CloudSyncOutlined /> 扫描局域网
      </Button>,
    );
    list.push(
      <Button type="dashed" onClick={stopScan} loading={loading}>
        <StopOutlined /> 停止扫描局域网
      </Button>,
    );
    return list;
  }, [loading, startScan, stopScan]);

  return (
    <PageContainer header={{ breadcrumb: {} }}>
      <HostInfoFormModal
        values={currData}
        visible={currData != null}
        setVisible={(v: any) => {
          if (!v) {
            setCurrData(undefined);
          }
        }}
      />
      <Spin spinning={loading}>
        <ProTable<NmapVo, API.PageParams>
          headerTitle="扫描结果列表"
          actionRef={actionRef}
          rowKey="ip"
          request={listNmap}
          onRequestError={(e: any) => {
            e.response.json().then((res: any) => message.error(res.msg));
          }}
          columns={columns}
          search={false}
          tableAlertRender={false}
          options={{ fullScreen: true, reload: true, setting: true }}
          toolBarRender={toolBarBtn}
        />
      </Spin>
    </PageContainer>
  );
};
